<?php
/**
 * 
 * Enter description here ...
 * @author Zijian Wang
 */

class Checkin_model extends CI_Model {

	function __construct()
	{
		// Call the Model constructor
		parent::__construct();
	}

  
	/**
	*
	* To create a checkin entry.
	* @param  $l_id
	* Note: In the frontend, the user transmits and storeds his/her latitude&longitude(by the function
	*       "location_model\insert_location")firstly. It generates a new location_id.
	* @param  $u_name, 
	* @param  $ci_time, checkin_time.  
	* @return ture/false
	*/
	function create_checkin($l_id,$u_name)
	{

		$ci_time = gmmktime();

		if( ($l_id == NUll) or ($u_name == NUll) or ($ci_time == NULL) )
		{
			//Insertion is invalid!
			return false;
		}

        $sql = "INSERT INTO checkin(l_id,u_name,ci_time) 
		VALUES ";
		$sql.= "(".$l_id.",'".$u_name."',".$ci_time.")"; 
		$result = $this->db->query($sql);
		return $result;
	}


   /**
	*
	* To create a route of checkins
	* @param  $u_name
	* Note: ci_time need to be changed into "HH:II:SS"
	* @return a serie of l_name,l_latitude,l_longtitude,ci_time, which are ordered by descending.
	*/

	function checkin_route($u_name)
	{

		if($u_name == NUll)
		{
			return false;
		}

        $sql = "SELECT l_name,l_latitude,l_longtitude,ci_time FROM location NATURAL JOIN checkin ";
		$sql.= "WHERE u_name = '".$u_name."' ORDER BY ci_time DESC"; 
		$q = $this->db->query($sql);
		$result = $q->result_array($q);
		return $result;
	}



   /**
	*
	* To list latest 10 checkins
	* @$start, $end; the scope of output
	* Note: ci_time need to be changed into "HH:II:SS"
	* @return a serie of l_name,l_latitude,l_longtitude,ci_time, which are ordered by descending.
	*/
	function latest_checkin($start=0,$end=10)
	{
		
        $sql = " SELECT u_name,u_username,l_name,l_latitude,l_longtitude,ci_time 
		        FROM location NATURAL JOIN checkin NATURAL JOIN user ";
		$sql.= " ORDER BY ci_time DESC ";
		$sql.= " LIMIT ".$start .','.$end;
		$q = $this->db->query($sql);
		$result = $q->result_array($q);
		return $result;
	}




	/**
	*
	* To output the total number of checkins sent by $u_name
	* @param  $u_name
	* @return a sum number.
	*/

	function checkin_count($u_name)
	{

		if( $u_name == NUll )
		{
			return false;
		}

		$sql = "SELECT COUNT(u_name) AS sum ";
        $sql.= "FROM checkin WHERE u_name = '".$u_name."'";

		$q = $this->db->query($sql);
		$result = $q->result_array($q);
		$temp= intval($result[0]['sum']);
		return $temp;
	}
}